package ai.moran.demo.common.aspect;

import ai.moran.demo.bo.SysLogEntity;
import ai.moran.demo.common.annotation.SysLog;
import ai.moran.demo.utils.HttpContextUtils;
import ai.moran.demo.utils.IPUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * 系统日志，切面处理类
 *
 */
@Aspect
@Component
@Slf4j
public class SysLogAspect {


    @Pointcut("@annotation(ai.moran.demo.common.annotation.SysLog)")
    public void logPointCut() {

    }

    @Around("logPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        //执行方法
        Object result = null;
        long time = 0;
        try {
            result = point.proceed();
            //执行时长(毫秒)
            time = System.currentTimeMillis() - beginTime;
        } catch (Throwable throwable) {
            saveSysLog(point, time, ExceptionUtils.getFullStackTrace(throwable));
            throw throwable;
        }

        //保存日志
        try {
            saveSysLog(point, time, result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    private void saveSysLog(ProceedingJoinPoint joinPoint, long time, Object result) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        SysLogEntity sysLog = new SysLogEntity();

        SysLog syslog = method.getAnnotation(SysLog.class);
        if (syslog != null) {
            //注解上的描述
            sysLog.setOperation(syslog.value());
        }

        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");

        //请求的参数
        Object[] args = joinPoint.getArgs();
        List<Object> list = new ArrayList<>();
        for (Object object : args) {
            if (!(object instanceof MultipartFile)) {
                list.add(object);
            }
        }
        String params = JSONObject.toJSONString(list);
        sysLog.setParams(params);

        //获取request
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        //设置IP地址
        sysLog.setIp(IPUtils.getIpAddr(request));

        //用户名
//        SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
        String username = "未登录用户";
//        if (null != sysUserEntity) {
//            username = sysUserEntity.getUsername();
//        }
        sysLog.setUsername(username);

        sysLog.setTime(time);
        sysLog.setCreateDate(new Date());

        sysLog.setResult(result);


        //保存系统日志
//		sysLogService.save(sysLog);
        log.info(JSONObject.toJSONStringWithDateFormat(sysLog, "yyyy-MM-dd HH:mm:ss.SSS"));
    }


}
